package com.base.interview.devtest.interceptor;

import com.base.interview.devtest.entity.UserEntity;
import com.base.interview.devtest.exception.AuthenticationException;
import com.base.interview.devtest.util.SessionManager;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login")) {
            return true;
        }

        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            throw new AuthenticationException("需要认证!");
        }
        UserEntity loggedIn = SessionManager.isLoggedIn(token);
        if (loggedIn == null) {
            throw new AuthenticationException("认证过期! 请登录");
        }
        SessionManager.refresh(token);
        SessionManager.setThreadUser(loggedIn.getId());
        return true;
    }
}
